import { useState, useEffect, useRef } from 'react';
export default function useCCThrottle(fn, wait = 500) {
  const [isLoading, setLoading] = useState(false);
  const [flag, setFlag] = useState(false);
  let timer = useRef()

  useEffect(() => {
    timer.current = isLoading;
    console.log('useThrottle...useEffect...load', isLoading, timer.current)
    return () => {
      console.log('useThrottle...useEffect...unload')
    };
  }, []);

  useEffect(() => {
    console.log('tiemr.vlaueChange...', timer.current)
    setLoading(!!timer.current)
  }, [timer.current])

  useEffect(() => {
    console.log('flagChange...', flag)
    // setLoading(!!timer.current)
  }, [flag])

  const throllteFn = (...arg) => {
    if (!timer.current) {
      fn.apply(this, arg)
      setFlag (true)
      timer.current = setTimeout(() => {
        setFlag (false)
        // 将timer.current致为null时,useEffect的监听会丢失
        // timer.current = null
        timer.current = false
      }, wait)
    }
  }
  return {
    isLoading,
    flag,
    throllteFn
  }
};